package com.example.ai.uploadImage;

import com.example.demo.ai.entity.Message;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.util.*;

public class QiniuAIClient {
    private static final String OPENAI_BASE_URL = "https://openai.qiniu.com/v1";
    private static final String OPENAI_API_KEY = "sk-97e3f74b4564015f0dc2f315f3d27a82a3507b4432c5a07e04e165a4178e5520";
    private static final String MODEL = "deepseek/deepseek-v3.1-terminus";
    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");


    private final OkHttpClient client;
    private final ObjectMapper objectMapper;

    public QiniuAIClient() {
        this.client = new OkHttpClient();
        this.objectMapper = new ObjectMapper();
    }

    // 流式响应处理
    public Map<String, String> streamChatCompletion(List<Message> messages) throws IOException {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", MODEL);
        requestBody.put("messages", messages);
        requestBody.put("stream", true);
        requestBody.put("max_tokens", 4096);

        String requestBodyJson = objectMapper.writeValueAsString(requestBody);

        Request request = new Request.Builder()
                .url(OPENAI_BASE_URL + "/chat/completions")
                .post(RequestBody.create(requestBodyJson, JSON_MEDIA_TYPE))
                .addHeader("Authorization", "Bearer " + OPENAI_API_KEY)
                .addHeader("Content-Type", "application/json")
                .build();

        StringBuilder contentBuilder = new StringBuilder();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code: " + response);
            }

            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                // 处理流式响应
                String[] lines = responseBody.string().split("\n");

                for (String line : lines) {
                    if (line.startsWith("data: ") && !line.equals("data: [DONE]")) {
                        String jsonData = line.substring(6); // 去掉 "data: " 前缀

                        try {
                            JsonNode jsonNode = objectMapper.readTree(jsonData);
                            JsonNode choices = jsonNode.get("choices");
                            if (choices != null && choices.isArray() && !choices.isEmpty()) {
                                JsonNode delta = choices.get(0).get("delta");
                                if (delta != null && delta.has("content")) {
                                    String chunkContent = delta.get("content").asText();
                                    contentBuilder.append(chunkContent);
                                    // 可选：实时输出
                                    System.out.print(chunkContent);
                                }
                            }
                        } catch (Exception e) {
                            // 忽略JSON解析错误，继续处理下一行
                        }
                    }
                }
            }
        }

        AdaptiveSceneParser  parser = new AdaptiveSceneParser ();
        return parser.parseScenes(contentBuilder.toString());
    }
}
